#!/usr/bin/wish
#type “wish find_replace.tcl” to run script

package require Tk

font create EmacDefaultFont -family Helvetica -size 16
option add *font EmacDefaultFont
ttk::style configure TFrame -font EmacDefaultFont ;#change TFrame style
ttk::style configure TButton -font EmacDefaultFont ;#change TButton style
ttk::style configure TCheckbutton -font EmacDefaultFont ;#change TCheckbutton style
ttk::style configure TLable -font EmacDefaultFont ;#change TLable style
ttk::style configure TEntry -font EmacDefaultFont ;#change TEntry style
ttk::style configure TRadiobutton -font EmacDefaultFont ;#change TRadiobutton style

wm title . "Change file names to lowercase"
frame .frame
grid .frame -row 0 -column 0

label .frame.lbl -text "path of directory:" -width 30
entry .frame.ent -textvariable dirPath -width 50
label .frame.lbl0 -text "Find text:" -width 30
entry .frame.ent0 -textvariable findText -width 30
label .frame.lbl1 -text "Replace with text:" -width 30
entry .frame.ent1 -textvariable replaceText -width 30
button .frame.btn1 -text "Replace" -width 8 -command {find_and_replace $dirPath $findText $replaceText 0}
button .frame.btn2 -text "Quit" -width 8 -command {exit}

grid .frame.lbl -row 0 -column 0 -sticky nsew
grid .frame.ent -row 0 -column 1 -columnspan 3 
grid .frame.lbl0 -row 1 -column 0 -sticky nsew
grid .frame.ent0 -row 1 -column 1 -columnspan 2 
grid .frame.lbl1 -row 2 -column 0 -sticky nsew
grid .frame.ent1 -row 2 -column 1 -columnspan 2 
grid .frame.btn1 -row 3 -column 2
grid .frame.btn2 -row 3 -column 3

proc find_and_replace {dir_name find_text replace_text level} {
    if {![file isdirectory $dir_name] || ![string length [string trim $find_text]]} {
        return -code error "directory $dir_name not exists or empty find text"
    }

    #set file_list [exec ls "$dir_name"] ;#file name not include path
    set file_list [glob -nocomplain -directory $dir_name *]

    foreach fl $file_list {
        if {[file isdirectory $fl]} {
            set sub_dir $fl 
            find_and_replace $sub_dir $find_text $replace_text [expr $level + 1]
        } elseif {[file isfile $fl]} {
            exec sed "-i" "s/$find_text/$replace_text/g" $fl
            puts "All \"$find_text\" are replaced with \"$replace_text\" in file: $fl !"
        } else {
            puts "unknown file type: $fl"
        }
    }

    if {$level == 0} {
        tk_messageBox -message "All \"$find_text\" are replaced with \"$replace_text\" in directory: $dir_name !"
    } else {
        puts "All \"$find_text\" are replaced with \"$replace_text\" in subdirectory: $dir_name !"
    }

    return
}

